package proxy

import (
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"

	"github.com/gin-gonic/gin"
)

func NewReverseProxy(targetURL string) (*httputil.ReverseProxy, error) {
	target, err := url.Parse(targetURL)
	if err != nil {
		return nil, err
	}

	proxy := httputil.NewSingleHostReverseProxy(target)

	// 自定义错误处理
	proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
		log.Printf("Proxy error: %v", err)
		http.Error(w, "Service unavailable", http.StatusServiceUnavailable)
	}

	// 修改响应头（可选）
	proxy.ModifyResponse = func(resp *http.Response) error {
		// 可移除敏感头
		resp.Header.Del("Server")
		return nil
	}

	// 修改请求路径，移除服务前缀
	originalDirector := proxy.Director
	proxy.Director = func(req *http.Request) {
		originalDirector(req)
		// 移除路径前缀
		if strings.HasPrefix(req.URL.Path, "/auth") {
			req.URL.Path = strings.TrimPrefix(req.URL.Path, "/auth")
			log.Printf("Rewritten path from /auth prefix to: %s", req.URL.Path)
		} else if strings.HasPrefix(req.URL.Path, "/task") {
			req.URL.Path = strings.TrimPrefix(req.URL.Path, "/task")
			log.Printf("Rewritten path from /task prefix to: %s", req.URL.Path)
		}
	}

	return proxy, nil
}

// GinProxyHandler 返回一个Gin处理函数，动态解析服务并代理
func GinProxyHandler(serviceName string) gin.HandlerFunc {
	return func(c *gin.Context) {
		log.Printf("Attempting to resolve service: %s", serviceName)
		addr, err := ResolveService(serviceName)
		if err != nil {
			log.Printf("Failed to resolve service %s: %v", serviceName, err)
			c.JSON(http.StatusServiceUnavailable, gin.H{"error": "No healthy instance", "service": serviceName, "reason": err.Error()})
			return
		}

		log.Printf("Resolved service %s to address: %s", serviceName, addr)
		targetURL := "http://" + addr
		log.Printf("Creating proxy to target URL: %s", targetURL)

		proxy, err := NewReverseProxy(targetURL)
		if err != nil {
			log.Printf("Failed to create proxy for service %s: %v", serviceName, err)
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Proxy setup failed", "service": serviceName, "target": targetURL, "reason": err.Error()})
			return
		}

		log.Printf("Forwarding request %s %s to %s", c.Request.Method, c.Request.URL.Path, targetURL)
		// 将Gin上下文转换为标准的http.ResponseWriter和*http.Request
		proxy.ServeHTTP(c.Writer, c.Request)
		log.Printf("Request forwarded to %s completed", targetURL)
	}
}
